<script lang="ts" setup>
import { addApi, queryApi, queryInfoApi, updataApi, deleteApi } from '@/api/user'
import { ref, watch, onMounted } from 'vue'
import type { ComponentSize } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'


//钩子函数 浏览器加载完成自动执行
onMounted(() => {
    onSubmit()
})


// 搜索栏数据对象
const users = ref({ name: '', gender: '', date: [], begin: '', end: '' })

// 侦听搜索栏对象的date属性
watch(() => users.value.date, (newVal, oldVal) => {
    if (newVal && newVal.length == 2) {
        users.value.begin = newVal[0];
        users.value.end = newVal[1];
    } else {
        users.value.begin = '';
        users.value.end = '';
    }
})

// 查询按钮
const onSubmit = async () => {
    try {
        const result = await queryApi(
            users.value.name,
            users.value.gender,
            users.value.begin,
            users.value.end,
            currentPage.value,
            pageSize.value
        );
        console.log(result);
        

        if (result && typeof result === 'object') {
            // 兼容不同格式的返回数据
            const data = result.data || result;
            userList.value = data.records || [];
            total.value = data.total || 0;
        } else {
            console.error('返回数据格式错误:', result);
            ElMessage.error('数据获取失败，请稍后重试');
        }
    } catch (error) {
        console.error('查询用户列表异常:', error);
        ElMessage.error('查询失败，请检查网络连接或联系管理员');
    }
}

// 表格数据
const userList = ref([])

// 清除按钮
const remove = () => {
    users.value = { name: '', gender: '', date: [], begin: '', end: '' }
}

// 编辑按钮
const edit = async (id) => {
    dialogVisible.value = true
    dialogTitle.value = '编辑用户'
    const result = await queryInfoApi(id)
    if (result) {
        newUser.value = result.data
    }

}

// 根据id删除按钮
const deleteById = async (id) => {

    //确认提示框
    ElMessageBox.confirm(
        '确定要删除该用户信息吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => { //确认 这里是点确认后该做什么功能
            //传递id给后端，并接收响应回来的数据
            const result = await deleteApi(id);
            if (result) {
                ElMessage.success('删除成功')
                //刷新数据
                onSubmit();
            } else {
                //使用返回的错误信息
                ElMessage.error('删除失败');
            }
        })
        .catch(() => { //取消 这里是点取消后该做什么功能
            ElMessage.info('你点击了取消删除');
        })
}

//批量删除用户信息
//记录勾选的员工的id
const selectedIds = ref([]);
const handleSelectionChange = (selection) => {
    selectedIds.value = selection.map(item => item.id);
}

//批量删除
const deleteByIds = () => {
    //弹出确认框
    ElMessageBox.confirm('您确认删除该员工吗?', '提示',
        { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => { //确认
        if (selectedIds.value && selectedIds.value.length > 0) {
            const result = await deleteApi(selectedIds.value);
            if (result) {
                ElMessage.success('删除成功');
                onSubmit();
            } else {
                ElMessage.error('删除失败');
            }
        } else {
            ElMessage.info('您没有选择任何要删除的数据');
        }
    }).catch(() => { //取消
        ElMessage.info('您已取消删除');
    })
}

// 添加用户
const adduser = () => {
    dialogVisible.value = true
    dialogTitle.value = '添加用户'
    newUser.value = {
        id: '',
        name: '',
        username:'',
        password:'',
        img: '',
        gender: '',
        phone: '',
        createdAt: ''
    }

    //重置表单的校验规则 --提示信息
    if (UserFromRef.value) {
        UserFromRef.value.resetFields();
    }
}

// 提交添加用户数据
const save = async () => {
    //判断是否通过检验
    if (!UserFromRef.value) return
    //检验通过后干什么
    UserFromRef.value.validate(async (valid) => {
        if (valid) {
            let result;
            if (newUser.value.id) {
                result = await updataApi(newUser.value)
            } else {
                result = await addApi(newUser.value)
            }
            if (result) {
                //成功
                ElMessage.success('保存成功');
                dialogVisible.value = false;
                onSubmit()
            } else {
                //失败
                ElMessage.error('保存失败');
            }
        }else{
            ElMessage.error('数据异常')
        }
    })
}



//分页条
// 初始页码
const currentPage = ref(1)
// 每页记录数
const pageSize = ref(10)
const size = ref<ComponentSize>('default')
const background = ref(true)
const disabled = ref(false)
const total = ref(0) // 页码总记录数

const handleSizeChange = (val: number) => {
    pageSize.value = val;
    onSubmit();
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    onSubmit();
}

// 添加/编辑弹框
const dialogVisible = ref(false)

// 弹窗标题
const dialogTitle = ref('添加用户')

//添加/编辑对象
const newUser = ref({
    id: '',
    username:'',
    password:'',
    name: '',
    img: '',
    gender: '',
    phone: '',
    createdAt: ''
})


//文件上传
// 图片上传成功后触发
const handleAvatarSuccess = (response, uploadFile) => {
    newUser.value.img = response.data
}
// 文件上传之前触发
const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('只支持上传图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('只能上传10M以内图片')
        return false
    }
    return true
}

//检验数据
const UserFromRef = ref()

//表单校验规则
const rules = ref({
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 5, message: '用户名长度应在2到5个字符之间', trigger: 'blur' }
    ],
     username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度应在2到20个字符之间', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ],
    password:[
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 2, max: 20, message: '密码长度应在6到12个数字之间', trigger: 'blur' }
    ]
});


</script>

<template>
    <h1>用户管理</h1>

    <!-- 搜索栏 -->
    <div class="container">
        {{ users }}
        <el-form :inline="true" :model="users" class="demo-form-inline">
            <!-- 根据用户名查询 -->
            <el-form-item label="用户名:">
                <el-input v-model="users.name" placeholder="请输入用户名" clearable />
            </el-form-item>


            <el-form-item label="性别:">
                <el-select v-model="users.gender" placeholder="请选择性别" clearable>
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>

            <!-- 根据时间查询 -->
            <el-form-item label="时间范围:">
                <el-date-picker v-model="users.date" type="daterange" range-separator="到" start-placeholder="开始时间"
                    end-placeholder="结束时间" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                <!--         searchEmp.date:绑定数据   daterange：时间范围属性  range-separator：设置中间的分割字样 start-placeholder：开始时间的提示语 end-placeholder：结束时间的提示语                                                                                                                                              -->
            </el-form-item>

            <!-- 查询和删除 -->
            <el-form-item>
                <el-button type="primary" @click="onSubmit">查询</el-button>
                <el-button type="danger" @click="remove">清除</el-button>
            </el-form-item>
        </el-form>
    </div>

    <!-- 功能部分 -->
    <div class="container">
        <el-button type="primary" @click="adduser">+ 添加用户</el-button>
        <el-button type="danger" @click="deleteByIds()">- 批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="container">
        <el-table :data="userList" border style="width: 100%" @selection-change="handleSelectionChange">
            <!-- 勾选复选框 -->
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="username" label="用户名" width="100" />
            <el-table-column label="头像" width="120" align="center">
                <template #default="scope">
                    <img :src="scope.row.img" height="50px">
                </template>
            </el-table-column>
            <el-table-column label="性别" width="120" align="center">
                <template #default="scope">
                    {{ scope.row.gender == 1 ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" width="180" />
            <el-table-column prop="createdAt" label="创建时间" width="180"/>
            <el-table-column prop="updatedAt" label="最后操作时间" width="180"/>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="edit(scope.row.id)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteById(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 分页条 -->
    <div class="container">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
            :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>


    <!-- 添加/编辑用户 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" center>
        {{ newUser }}
        <el-form :model="newUser" label-width="auto" style="max-width: 600px" :rules="rules" ref="UserFromRef">
            <el-form-item label="添加用户名:" prop="username">
                <el-input v-model="newUser.username" placeholder="请输入用户名" />
            </el-form-item>
                 <el-form-item label="添加姓名:" prop="name">
                <el-input v-model="newUser.name" placeholder="请输入姓名" />
            </el-form-item>
                 <el-form-item label="添加密码:" prop="password">
                <el-input v-model="newUser.password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="性别:" prop="gender">
                <el-select v-model="newUser.gender" placeholder="请选择性别" clearable>
                    <el-option label="男" value="1" />
                    <el-option label="女" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="添加手机号:" prop="phone">
                <el-input v-model="newUser.phone" placeholder="请输入手机号" />
            </el-form-item>

            <el-form-item label="头像">
                <el-upload class="avatar-uploader" action="/api/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="newUser.img" :src="newUser.img" class="avatar" height="50px" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>


        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style>
.container {
    margin: 15px 0;
}
</style>